const axios = require('axios')
const https = require('https')
const FormData = require('form-data')
const { getRequestContext } = require('../config/asyncContext')
const { webEnvironment } = require('../config/index')
const { REMOTE_EXEC_API_KEY, REMOTE_EXEC_API_SECRET } = process.env
const REMOTE_EXEC_AUTH = `${Buffer.from(`${REMOTE_EXEC_API_KEY}:${REMOTE_EXEC_API_SECRET}`).toString('base64')}`

axios.defaults.withCredentials = true
axios.defaults.proxy = false
//创建默认的axios实例
const axiosInstance = axios.create({
  httpsAgent: new https.Agent({
    rejectUnauthorized: false
  })
})

axiosInstance.interceptors.request.use(config => {
  const { headers, data } = config
  if (data instanceof FormData) {
    Object.assign(headers, data.getHeaders())
  }

  headers['Authorization'] = `Basic ${REMOTE_EXEC_AUTH}`
  const ctx = getRequestContext()
  config.baseURL = webEnvironment[ctx?.headers?.env]?.remoteExecBaseURL
  return config
})

axiosInstance.interceptors.response.use(({ data }) => data, err => {
  const { config, response } = err
  const { code, message, requestId } = response?.data || {}
  Object.assign(err, {
    message: `${err.message}. RequestId: ${config?.headers?.['X-Request-ID'] || requestId}`,
    code,
    detail: message
  })
  return Promise.reject(err)
})

module.exports = axiosInstance